package pl.edu.mimuw.mas.agent.behaviour.deer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.mimuw.mas.agent.DeerAgent;
import pl.edu.mimuw.mas.agent.behaviour.MutableTimedBehaviour;
import pl.edu.mimuw.mas.util.FearSource;
import pl.edu.mimuw.mas.util.Position;
import pl.edu.mimuw.mas.util.PositionHelper;
import pl.edu.mimuw.mas.util.Time;

public class DestinationBehaviour extends MutableTimedBehaviour {

	private static final long serialVersionUID = 3355170333279741470L;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	public DestinationBehaviour(DeerAgent a) {
		super(a, Time.DEER_DEST);
	}

	protected void onTick() {
		DeerAgent a = (DeerAgent) myAgent;
		// czyszcze nieaktualne zrodla strachu
		a.organizeFearSources();
		// skoro wszystko aktualne to patrzymy gdzie iść
		Position dest;
		if (a.getFearSources().size() > 0) {
			dest = getFleeDestination();
		} else {
			dest = PositionHelper.getRandomPosition(a);
		}
		a.getDest().x = dest.x;
		a.getDest().y = dest.y;
	}

	private Position getFleeDestination() {
		DeerAgent a = (DeerAgent) myAgent;
		Position sourceAvgPos = new Position(0, 0);
		Position p = a.getPosition();

		long smallestTimeout = Long.MAX_VALUE;
		for (FearSource fs : a.getFearSources()) {
			sourceAvgPos.x += fs.position.x;
			sourceAvgPos.y += fs.position.y;
			if (fs.timeout < smallestTimeout) {
				smallestTimeout = fs.timeout;
			}
		}
		sourceAvgPos.x /= a.getFearSources().size();
		sourceAvgPos.y /= a.getFearSources().size();

		float sourceDeerDist = PositionHelper.getDistance(sourceAvgPos, p);
		float destDeerDist = Math.max(smallestTimeout - System.currentTimeMillis(), 
				Time.DEER_DEST)	/ Time.DEER_STEP_MIN;
		float fact = destDeerDist / sourceDeerDist;

		Position dest = new Position(p.x + (int)((p.x - sourceAvgPos.x) * fact),
				p.y + (int)((p.y - sourceAvgPos.y) * fact));

		return dest;
	}
}
